package com.example.endwork;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.dao.DBHelp;
import com.dao.DBoperate;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.items.person;
import com.operate.addData;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class page2 extends AppCompatActivity {

    private EditText name;
    private EditText p1;
    private EditText p2;
    private FloatingActionButton calll;
    private FloatingActionButton callr;
    private FloatingActionButton save;
    private FloatingActionButton del;
    private FloatingActionButton out;//导出数据
    private FloatingActionButton in;//导入数据
    private String type;//本界面类型
    private DBoperate dboperate;
    private Intent intent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_page2);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        this.dboperate=new DBoperate(new DBHelp(this));
        intent = getIntent();
        type = intent.getStringExtra("type");
        //初始化界面
        init();
        //保存添加一个监听器
        this.save_Listener();
        this.del_Listener();
        this.calllListener();
        this.callrListener();
        this.datap();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            if (data!= null) {
                Uri uri = data.getData();
                if(uri!=null) {
                    try {
                        String content = readTextFromUri(uri);
                        // 在这里可以对读取到的文件内容进行处理，如显示在TextView中
                        Log.d("FileContent", content);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private String readTextFromUri(Uri uri) throws IOException {
//        StringBuilder stringBuilder=new StringBuilder();
        InputStream inputStream=getContentResolver().openInputStream(uri);
        BufferedReader reader=new BufferedReader(new InputStreamReader((inputStream)));
        String line;
        person p;
        while((line=reader.readLine())!=null){
            String[] array=line.split(",");
            p=new person(Integer.parseInt(array[0]),array[1],array[2],array[3]);
            boolean result=dboperate.addData(p);//向数据库中添加数据
            if(!result){
                Toast.makeText(page2.this,"数据项["+line+"]插入失败",Toast.LENGTH_SHORT).show();
            }
        }
        Toast.makeText(page2.this,"数据导入完成",Toast.LENGTH_SHORT).show();
        return "";
    }

    private void writeFile() throws IOException {
        File path= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
//        path=getDataDir();
        File file=new File(path,"通讯录导出数据.txt");//保存位置
        if(!path.exists()){
            path.mkdirs();
        }
        if(!file.exists()){
            //如果文件不存在就创建文件
            file.createNewFile();
        }
        List<person> result=dboperate.getAll();//获取数据库所有数据
        BufferedWriter writer =new BufferedWriter(new FileWriter(file,true));
        for(int i=0;i<result.size();i++){
            person t=result.get(i);
            writer.write(t.getId()+","+t.getName()+","+t.getPhone_1()+","+t.getPhone_2()+"\n");
        }
        writer.close();
        Toast.makeText(page2.this,"数据写入在"+file.getAbsolutePath(),Toast.LENGTH_SHORT).show();
    }

    private void datap(){
        in.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //导入数据
                //启动选择文件
                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                intent.setType("text/plain");
                startActivityForResult(intent, 1);
            }
        });
        //导出按钮
        out.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    writeFile();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

    private void calllListener(){
        //左边打电话
        calll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String phoneNumber=p1.getText().toString();
                Intent diaintent=new Intent(Intent.ACTION_DIAL);
                diaintent.setData(Uri.parse("tel:"+phoneNumber));
                startActivity(diaintent);
            }
        });
    }
   private void callrListener(){
        //左边打电话
        callr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String phoneNumber=p2.getText().toString();
                Intent diaintent=new Intent(Intent.ACTION_DIAL);
                diaintent.setData(Uri.parse("tel:"+phoneNumber));
                startActivity(diaintent);
            }
        });
    }


    private void save_Listener(){
        this.save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //保存数据
                String nameValue=name.getText().toString();
                String p1Value=p1.getText().toString();
                String p2Value=p2.getText().toString();
                //添加数据
                if(nameValue.isBlank()){
                    //如果姓名为空
                    new MaterialAlertDialogBuilder(page2.this)
                            .setTitle("提示")
                            .setMessage("你不能将姓名设置为空值")
                            .setPositiveButton("确定", (dialog, which) -> {
                                // 用户点击了确定
                            })
                            .setNegativeButton("取消", (dialog, which) -> {
                                // 用户点击了取消
                            })
                            .show();
                    return ;
                }
                //先确认用户是否存在
                if(dboperate.search(nameValue,"姓名")!=null){
                    //说明用户存在，就不能重复添加
                    Toast.makeText(page2.this,"添加失败，该用户已存在",Toast.LENGTH_SHORT).show();
                    return;
                }
                person p=new person(nameValue,p1Value,p2Value);
                if(dboperate.addData(p)){
                    Toast.makeText(page2.this, "添加成功", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(page2.this,"添加失败",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void del_Listener(){
        //删除监听器
        this.del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String nameValue=name.getText().toString();
                String p1Value=p1.getText().toString();
                String p2Value=p2.getText().toString();
                person value=new person(nameValue,p1Value,p2Value);

                new MaterialAlertDialogBuilder(page2.this)
                        .setTitle("确认操作")
                        .setMessage("你确定要执行此操作吗？此联系人将被删除")
                        .setPositiveButton("确定", (dialog, which) -> {
                            // 用户点击了确定
                            String res;
                            if(dboperate.deleteData(value)){
                                res="删除成功";
                                name.setText("");
                                p1.setText("");
                                p2.setText("");
                            }
                            else{
                                res="删除失败";
                            }
                            Toast.makeText(page2.this,res,Toast.LENGTH_SHORT).show();})
                        .setNegativeButton("取消", (dialog, which) -> {
                            // 用户点击了取消
                            Toast.makeText(page2.this, "已取消", Toast.LENGTH_SHORT).show();
                        })
                        .show();

            }
        });
    }

    private void init(){
        //这是初始化按钮
        this.name=(EditText) findViewById(R.id.name);
        this.p1=(EditText) findViewById(R.id.p1);
        this.p2=(EditText) findViewById(R.id.p2);
        this.calll=findViewById(R.id.calll);
        this.callr=findViewById(R.id.callr);
        this.save=findViewById(R.id.save);
        this.del=findViewById(R.id.del);
        this.in=findViewById(R.id.in);
        this.out=findViewById(R.id.out);
        if(this.type!=null&&this.type.equals("E")){//如果是新添加状态,电话按钮不可见
            this.calll.setVisibility(View.INVISIBLE);
            this.callr.setVisibility(View.INVISIBLE);
            this.del.setVisibility(View.INVISIBLE);
        }else{//这是是原来就有数据，需要显示
            //导入导出数据按钮隐藏
            this.in.setVisibility(View.INVISIBLE);
            this.out.setVisibility(View.INVISIBLE);
            String nameT=intent.getStringExtra("name");
            String p1T=intent.getStringExtra("p1");
            String p2T=intent.getStringExtra("p2");
            this.name.setText(nameT);
            this.p1.setText(p1T);
            this.p2.setText(p2T);
        }

    }



}